<template>
    <div>
      <!-- 面包屑导航器 -->
      <el-breadcrumb separator="/">
        <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
        <el-breadcrumb-item><a href="/">权限管理</a></el-breadcrumb-item>
        <el-breadcrumb-item>角色列表</el-breadcrumb-item>
      </el-breadcrumb>

      <!-- 卡片视图区 -->
      <el-card >
        <!-- 添加区 -->
        <el-row >
          <el-col>
            <el-button @click="showAddDialogVisible" type="primary">添加角色</el-button>
          </el-col>
        </el-row>
        <!-- 角色列表区 -->
        <el-table :data="rolesList" style="width: 100%" border stripe>
          <!-- 展开列 -->
          <el-table-column type="expand" label="展开">
             <template slot-scope="scope">
               <!-- 权限列表 -->
               <el-row :class="['bdbuttom',i1===0 ?'bdtop':'','vcenter']" v-for="(item1,i1) in scope.row.children" :key="item1.id">
                  <!-- 一级权限 -->
                  <el-col :span="5">
                     <el-tag closable  @close="removeRightById(scope.row,item1.id)">{{item1.authName}}</el-tag>
                     <i class="el-icon-caret-right"></i>
                  </el-col>
                   <!-- 二级和三级权限 -->
                  <el-col :sapn="19">
                     <!-- 渲染二级权限 -->
                     <el-row :class="[i2===0? '':'bdtop','vcenter']" v-for="(item2,i2) in item1.children" :key="item2.id">
                        <el-col :span="6">
                           <el-tag closable  @close="removeRightById(scope.row,item2.id)" type="success">{{item2.authName}}</el-tag>
                           <i class="el-icon-caret-right"></i>
                        </el-col>
                        <!-- 三级标签 -->
                        <el-col :span="18">
                             <el-tag closable @close="removeRightById(scope.row,item3.id)" type="warning" v-for="(item3) in item2.children" :key="item3.id">{{item3.authName}}</el-tag>
                        </el-col>
                     </el-row>
                  </el-col>
               </el-row>
             </template>
          </el-table-column>
          <!-- 索引页 -->
          <el-table-column  type="index" >
          </el-table-column>
          <el-table-column prop="roleName" label="角色名称" >
          </el-table-column>
          <el-table-column prop="roleDesc" label="角色描述" >
          </el-table-column>
          <el-table-column label="操作"  width="300px">
            <template slot-scope="scope">
              <!--修改按钮-->
              <el-tooltip  effect="dark" content="编辑角色信息" placement="top-start"  :enterable="false">
                <el-button @click="showEditDialog(scope.row.id)" type="primary" icon="el-icon-edit" size="mini">编辑</el-button>
              </el-tooltip>
              <!--删除按钮-->
              <el-tooltip  effect="dark" content="删除角色" placement="top-start"  :enterable="false">
                <el-button type="danger" @click="removeRoleById(scope.row.id)" icon="el-icon-delete"  size="mini" >删除</el-button>
              </el-tooltip>
              <!--分配权限-->
              <el-tooltip  effect="dark" content="权限分配" placement="top-start"  :enterable="false">
                <el-button type="warning" @click="showSetRightDialog(scope.row)" icon="el-icon-setting" size="mini">权限分配</el-button>
              </el-tooltip>
            </template>
          </el-table-column>
        </el-table>
      </el-card>

      <!-- 添加角色的对话框-->
      <el-dialog
        title="添加用户"
        :visible.sync="addDialogVisible"
        width="50%"
        @close="addDialogClosed">
        <!--内容主体区域-->
        <el-form :model="addRolesList" :rules="addRolesRules" ref="addRolesRef" label-width="80px">
          <el-form-item label="用户名" prop="roleName">
            <el-input v-model="addRolesList.roleName"></el-input>
          </el-form-item>
          <el-form-item label="用户描述" prop="roleDesc">
            <el-input v-model="addRolesList.roleDesc"></el-input>
          </el-form-item>
        </el-form>
        <span slot="footer" class="dialog-footer">
          <!--内容底部按钮区域 点击了就隐藏对话框-->
        <el-button @click="addDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="addRoles">确 定</el-button>
        </span>
      </el-dialog>
      <!-- 修改角色信息的对话框-->
      <el-dialog
        title="修改用户"
        :visible.sync="editDialogVisible"
        width="50%"
        @close="editDialogClosed">
        <!--内容主体区域-->
        <el-form :model="editRoleList" :rules="editRoleRules" ref="editRoleRef" label-width="80px">
          <el-form-item label="角色名" prop="roleName" >
            <el-input v-model="editRoleList.roleName" ></el-input>
          </el-form-item>
          <el-form-item label="角色描述" prop="roleDesc">
            <el-input v-model="editRoleList.roleDesc"></el-input>
          </el-form-item>
        </el-form>
        <span slot="footer" class="dialog-footer">
          <!--内容底部按钮区域 点击了就隐藏对话框-->
        <el-button @click="editDialogVisible = false">取 消</el-button>
        <el-button  @click="editRolesInfo" type="primary">确 定</el-button>
        </span>
      </el-dialog>
      <!-- 分配权限的对话框-->
      <el-dialog
        title="分配权限"
        :visible.sync="SetRightDialogVisible"
        width="50%"
       @close="setRightDialogClosed">
        <!--内容主体区域-->
        <el-tree :data="rightsList" :props="treeProps" show-checkbox node-key="id"  ref="treeRef"  :default-expand-all="true" :default-checked-keys="defKeys"></el-tree>
        <span slot="footer" class="dialog-footer">
          <!--内容底部按钮区域 点击了就隐藏对话框-->
        <el-button @click="SetRightDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="addotRights" >确 定</el-button>
        </span>
      </el-dialog>
    </div>
</template>

<script>
export default {
  data () {
    return {
      rolesList: [],
      addRolesList: {
        roleName: '',
        roleDesc: ''
      },
      // 添加角色的输入规则
      addRolesRules: {
        roleName: [
          { required: true, message: '请输入角色名', trigger: 'blur' }
        ],
        roleDesc: [
          { required: true, message: '请输入角色描述', trigger: 'blur' }
        ]
      },
      // 控制编辑对话框的属性
      editDialogVisible: false,
      // 控制添加角色的对话框
      addDialogVisible: false,
      editRoleList: {},
      // 修改角色的验证规则
      editRoleRules: {
        roleName: [
          { required: true, message: '请输入角色名', trigger: 'blur' }
        ],
        roleDesc: [
          { required: true, message: '请输入角色描述', trigger: 'blur' }
        ]
      },
      // 控制分配权限的显示的属性
      SetRightDialogVisible: false,
      // 所有权限的数据
      rightsList: [],
      // 树形控件属性绑定对象
      treeProps: {
        label: 'authName',
        children: 'children'
      },
      // 默认选择的节点id值
      defKeys: [],
      // 当前即将分配权限的id
      roleId: ''
    }
  },
  created () {
    this.getRolesList()
  },
  methods: {
    // 获取所有角色列表数据
    async getRolesList () {
      const { data: res } = await this.$http.get('roles')
      if (res.meta.status !== 200) return this.$message.error('获取数据失败')
      this.rolesList = res.data
    },
    // 打开添加角色对话框
    showAddDialogVisible () {
      // 打开对话框
      this.addDialogVisible = true
    },
    // 修改角色信息
    async showEditDialog (id) {
      // 打开对话框
      this.editDialogVisible = true
      // 根据id查询然后显示到编辑页面
      const { data: res } = await this.$http.get('roles/' + id)
      if (res.meta.status !== 200) return this.$message.error('编辑异常')
      console.log(res.data.roleName)
      this.editRoleList = res.data
    },
    // 添加角色
    async addRoles () {
      const { data: res } = await this.$http.post('roles', {
        roleName: this.addRolesList.roleName,
        roleDesc: this.addRolesList.roleDesc
      })
      if (res.meta.status !== 201) {
        return this.$message.error('添加角色失败')
      }
      // 更新列表
      this.getRolesList()
      this.$message.success('添加角色成功')
      // 关闭对话框
      this.addDialogVisible = false
    },
    // 监听对话框关闭事件 重置表单
    addDialogClosed () {
      this.$refs.addRolesRef.resetFields()
    },
    // 监听修改用户对话框的事情
    editDialogClosed () {
      this.$refs.editRoleRef.resetFields()
    },
    // 修改角色相关属性
    async editRolesInfo () {
      this.$refs.editRoleRef.validate(async valid => {
        if (!valid) return this.$message.error('更新异常')
        // 发起修改用户的请求
        console.log(this.editRoleList.id)
        const { data: res } = await this.$http.put('roles/' + this.editRoleList.id, {
          roleName: this.editRoleList.roleName,
          roleDesc: this.editRoleList.roleDesc
        })
        if (res.meta.status !== 200) return this.$message.error('更新角色信息失败')
        this.editDialogVisible = false
        this.getRolesList()
        this.$message.success('更新角色信息成功')
      })
    },
    // 根据id删除角色
    async removeRoleById (id) {
      // 先打开对话框
      const confirmResult = await this.$confirm('此操作将永久删除该角色信息, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).catch(err => {
        return err
      })
      // 用户点删除 返回confirm  点击取消返回 cancel
      if (confirmResult !== 'confirm') {
        return this.$message.info('已经取消删除')
      }
      // 删除操作
      const { data: res } = await this.$http.delete('roles/' + id)
      if (res.meta.status !== 200) return this.$message.error('删除角色失败')
      this.$message.success('删除角色成功')
      this.getRolesList()
    },
    // 根据id删除对应权限
    async removeRightById (role, rightId) {
      // 先打开对话框
      const confirmResult = await this.$confirm('此操作将永久删除该角色权限, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).catch(err => {
        return err
      })
      // 用户点删除 返回confirm  点击取消返回 cancel
      if (confirmResult !== 'confirm') {
        return this.$message.info('已经取消删除')
      }
      // 删除操作
      const { data: res } = await this.$http.delete(`roles/${role.id}/rights/${rightId}`)
      if (res.meta.status !== 200) return this.$message.error('删除权限失败')
      role.children = res.data
      this.$message.success('删除权限成功')
    },
    // 展示权限分配的对话框并且获取数据
    async showSetRightDialog (role) {
      // 获取所有权限的数据
      const { data: res } = await this.$http.get('rights/tree')
      if (res.meta.status !== 200) return this.$message.error('获取权限数据失败')
      this.rightsList = res.data
      this.roleId = role.id
      this.getLeafKeys(role, this.defKeys)
      // 显示对话框
      this.SetRightDialogVisible = true
    },
    // 获取所有3级权限的id
    getLeafKeys (node, arr) {
      if (!node.children) {
        // 如果当前node不包含children属性则保存id
        return arr.push(node.id)
      }
      node.children.forEach(item => this.getLeafKeys(item, arr))
    },
    // 监听权限分配对话框的关闭
    setRightDialogClosed () {
      // 重置权限数组
      this.defKeys = []
    },
    // 更新权限
    async addotRights () {
      const keys = [
        ...this.$refs.treeRef.getCheckedKeys(),
        ...this.$refs.treeRef.getHalfCheckedKeys()
      ]
      const idStr = keys.join(',')
      // 调用更新接口
      const { data: res } = await this.$http.post(`roles/${this.roleId}/rights`, { rids: idStr })
      if (res.meta.status !== 200) return this.$message.error('更新权限失败')
      this.$message.success('分配权限成功')
      this.getRolesList()
      this.SetRightDialogVisible = false
    }
  }
}
</script>

<style scoped>
  .el-tag{
     margin: 7px;
  }
  .bdtop{
     border-top: 1px solid #eee;
  }
  .bdbuttom{
     border-bottom: 1px solid #eee;
  }
  .vcenter{
    display: flex;
    align-items: center;
  }
</style>
